<template>
  <div class="admin-accounts-container">
    <h1>管理后台账户</h1>
    <div v-if="error" class="error-message">{{ error }}</div> <!-- 添加错误信息显示 -->
    <div v-if="hasPermission">
      <form @submit.prevent="addAccount" class="add-account-form">
        <input v-model="newUsername" placeholder="用户名" class="add-account-input" />
        <input v-model="newRole" placeholder="角色" class="add-account-input" />
        <button type="submit" class="add-account-button">添加用户</button>
      </form>
      <table class="accounts-table">
        <thead>
          <tr>
            <th>用户名</th>
            <th>角色</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="account in accounts" :key="account.id">
            <td>{{ account.username }}</td>
            <td>{{ account.role }}</td>
            <td>
              <button @click="editAccount(account)">编辑</button>
              <button @click="deleteAccount(account.id)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div v-else class="error-message">您没有权限访问此页面</div> <!-- 添加权限不足提示 -->
    <div v-if="message" class="message">{{ message }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const accounts = ref([]);
const message = ref('');
const error = ref('');
const hasPermission = ref(false); // 添加权限变量
const newUsername = ref('');
const newRole = ref('');

const fetchAccounts = async () => {
  if (!hasPermission.value) {
    error.value = '您没有权限访问此页面';
    return;
  }
  try {
    const response = await axios.get('http://127.0.0.1:5000/AdminAccounts');
    accounts.value = response.data;
  } catch (error) {
    error.value = '获取账户信息失败，请稍后再试'; // 更新错误信息变量
    console.error('获取账户信息失败:', error); // 输出错误信息到控制台
  }
};

const addAccount = async () => {
  try {
    const response = await axios.post('http://127.0.0.1:5000/AdminAccounts', { username: newUsername.value, role: newRole.value });
    accounts.value.push(response.data);
    newUsername.value = '';
    newRole.value = '';
    message.value = '用户添加成功';
  } catch (error) {
    message.value = '添加用户失败，请稍后再试';
    console.error('添加用户失败:', error);
  }
};

const editAccount = (account) => {
  // 编辑账户逻辑
  console.log('编辑账户:', account);
};

const deleteAccount = async (accountId) => {
  try {
    await axios.delete(`http://127.0.0.1:5000/AdminAccounts/${accountId}`);
    accounts.value = accounts.value.filter(account => account.id !== accountId);
    message.value = '账户删除成功';
  } catch (error) {
    message.value = '删除账户失败，请稍后再试';
    console.error('删除账户失败:', error);
  }
};

const checkPermission = () => {
  // 这里可以添加实际的权限检查逻辑
  // 例如从 Vuex store 或 localStorage 获取用户权限
  hasPermission.value = true; // 示例中假设用户有权限
};

onMounted(() => {
  checkPermission();
  if (hasPermission.value) {
    fetchAccounts();
  }
});
</script>

<style scoped>
@import "../styles/AdminAccounts.css";
</style>